package com.wabbei.friendcenter.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.webbei.friendcenter.service.MyFriendCenter;

public class CustomUploadFileAction {
	private int customId;
	private MyFriendCenter friservice;
	private File files;
	private String  filesFileName;
	private String toName;
	private String realPath;
	
	public String execute(){
		//System.out.println("fileName111:"+filesFileName+"customId11:"+customId);
		System.out.println(toName);
		filesFileName=ReNameUtil.GetNewName()+filesFileName.substring(filesFileName.indexOf("."),filesFileName.length());
		System.out.println(filesFileName);
		boolean b=copyFile(files,toName,filesFileName);
		if(b){
			//update the customUploadFile in customs table
			String newFilePath=realPath+"\\"+filesFileName;
			String CustomUploadFileContent=friservice.getCustomUploadFileContentInCustoms(customId);
			int i=friservice.CustomUploadFileUpdateByCustomId(customId,CustomUploadFileContent+","+newFilePath);
			if(i>0){
				System.out.println("update success");
			}else{
				System.out.println("update fail");
			}
		}else{
			//do nothing.....
		}
		return null;
	}
	
	
	public boolean copyFile(File f, String toName,String fName){
		boolean b=true;
		if(f!=null){
			    realPath=ServletActionContext.getServletContext().getRealPath("/"+toName);
				System.out.println(realPath);
				File newFile=new File(realPath);
				if(!newFile.exists()){
					newFile.mkdirs();
				}
				try {
					FileUtils.copyFile(f,new File(newFile,fName));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println("send file successful");
		}else{
			b=false;
		}
		return b;
	}
	
	public MyFriendCenter getFriservice() {
		return friservice;
	}

	public void setFriservice(MyFriendCenter friservice) {
		this.friservice = friservice;
	}

	public File getFiles() {
		return files;
	}

	public void setFiles(File files) {
		this.files = files;
	}

	public String getFilesFileName() {
		return filesFileName;
	}

	public void setFilesFileName(String filesFileName) {
		this.filesFileName = filesFileName;
	}

	public int getCustomId() {
		return customId;
	}

	public void setCustomId(int customId) {
		this.customId = customId;
	}

	public String getToName() {
		return toName;
	}
	public void setToName(String toName) {
		this.toName = toName;
	}
	
}
